package cn.schoolwow.util.module.query.instanceList.flow.filter;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;
import cn.schoolwow.util.module.query.instanceList.domain.InstanceListQueryOption;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;

public class FilterInstanceByFieldValueFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        InstanceListQueryOption instanceQueryOption = flowContext.checkInstanceData(InstanceListQueryOption.class);
        List<Object> filterInstanceList = (List<Object>) flowContext.getData("filterInstanceList");

        if(null==instanceQueryOption.fieldValueMap){
            return;
        }
        Set<Collection<String>> keySet = instanceQueryOption.fieldValueMap.keySet();
        filterInstanceList.removeIf(instance->{
            for(Collection<String> fieldNames:keySet){
                Object fieldValue = null;
                if(fieldNames.size()==1){
                    String fieldName = fieldNames.iterator().next();
                    fieldValue = QueryInstance.newQuery(instance).execute().getSingleFieldValue(fieldName);
                }else{
                    fieldValue = QueryInstance.newQuery(instance).execute().getMultipleFieldValue(fieldNames);
                }
                Object expectValue = instanceQueryOption.fieldValueMap.get(fieldNames);
                if(!Objects.equals(fieldValue,expectValue)){
                    return true;
                }
            }
            return false;
        });
    }

    @Override
    public String name() {
        return "根据实例字段值过滤";
    }
}
